package edu.ntu.im.p2ptrade.action;

import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.TransactionManager;
import edu.ntu.im.p2ptrade.entity.Item;
import edu.ntu.im.p2ptrade.entity.ItemRepository;
import edu.ntu.im.p2ptrade.entity.PeerItemRepository;
import edu.ntu.im.p2ptrade.entity.Transaction;

public class SendTransactionRequest extends AjaxAction {

	@Override
	public AjaxResponse execute(HttpServletRequest request) {
		String myItemIds = request.getParameter("myIds");
		String peerItemIds = request.getParameter("peerIds");
		String peer = request.getParameter("peer");
		Transaction.TradeInfo infoMy = new Transaction.TradeInfo(P2PTrade.getInstance().getPeerName());
		List<Item> myItems = new LinkedList<Item>();
		StringTokenizer stMyIds = new StringTokenizer(myItemIds, ",");
		
		while (stMyIds.hasMoreTokens()){
			String idStr = stMyIds.nextToken();
			Item item = ItemRepository.getInstance().getItem(Integer.parseInt(idStr));
			myItems.add(item);
		}
		Transaction.TradeInfo infoPeer = new Transaction.TradeInfo(peer);
		List<Item> peerItems = new LinkedList<Item>();
		StringTokenizer stPeerIds = new StringTokenizer(peerItemIds, ",");
		while (stPeerIds.hasMoreTokens()){
			String idStr = stPeerIds.nextToken();
			Item item = PeerItemRepository.getInstance().getItem(peer, Integer.parseInt(idStr));
			peerItems.add(item);
		}
		infoMy.setItems(myItems);
//		infoMy.setOwner(P2PTrade.getInstance().getPeerName());
		infoPeer.setItems(peerItems);
//		infoPeer.setOwner(peer);
		TransactionManager.getInstance().issueTransactionRequest(infoMy, infoPeer);
		return success();
	}

}
